package com.fzg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fzg.common.enums.ResponseWrapper;
import com.fzg.common.model.jobInfoManage.param.*;
import com.fzg.common.model.jobInfoManage.result.*;
import com.fzg.common.tool.CommonTool;
import com.fzg.common.tool.ToolForDateTime;
import com.fzg.entity.Enterprise;
import com.fzg.entity.JobInfor;
import com.fzg.entity.User;
import com.fzg.entity.UserJob;
import com.fzg.mapper.EnterpriseMapper;
import com.fzg.mapper.JobInforMapper;
import com.fzg.mapper.UserJobMapper;
import com.fzg.mapper.UserMapper;
import com.fzg.service.JobInforService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 求职信息表 服务实现类
 * </p>
 *
 * @author fzg
 * @since 2021-12-13
 */
@Service
public class JobInforServiceImpl extends ServiceImpl<JobInforMapper, JobInfor> implements JobInforService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private JobInforMapper jobInforMapper;

    @Autowired
    private UserJobMapper userJobMapper;

    @Autowired
    private EnterpriseMapper enterpriseMapper;



    @Override
    public ResponseWrapper getJobInfoList(GetJobInfoListParam param) {

        // 加工页码
        param.setPage((param.getPage() - 1) * param.getPageRow()); //处理分页条件

        // 加工搜索条件（求职用户）
        if (param.getHuntUser() != null && !param.getHuntUser().equals("")){
            param.setHuntUser("%" + param.getHuntUser() + "%");
        }

        // 加工搜索条件（求职岗位）
        if (param.getPosName() != null && !param.getPosName().equals("")){
            param.setPosName("%" + param.getPosName() + "%");
        }

        // 返回结果
        GetJobInfoListResult result = new GetJobInfoListResult();

        ArrayList<GetJobInfoListResultReal> jobInfoList = new ArrayList<>();

        // account查询当前用户是否是管理员
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getIsAdmin, 1)
                .eq(User::getAccountNumber, param.getAccount()));
        if (user != null){
            // 管理员就查询所有用户的求职信息
            Integer totalNum = jobInforMapper.getAllJobInfoTotalNumByAdmin(param);
            result.setTotalNum(totalNum);

            List<Map<String, Object>> allJobInfoListMap = jobInforMapper.getAllJobInfoByAdmin(param);
            List<GetJobInfoListResultItem> allJobInfoList = CommonTool.mapListToBeanList(allJobInfoListMap, GetJobInfoListResultItem.class);

            for (GetJobInfoListResultItem item : allJobInfoList) {
                GetJobInfoListResultReal jobInfoListResultItem = new GetJobInfoListResultReal();
                jobInfoListResultItem.setAid(item.getAid());
                jobInfoListResultItem.setHuntUser(item.getHuntUser());
                if (item.getGender() == 1){
                    jobInfoListResultItem.setGender("男");
                }else {
                    jobInfoListResultItem.setGender("女");
                }
                jobInfoListResultItem.setPhone(item.getPhone());
                jobInfoListResultItem.setPosName(item.getPosName());
                jobInfoListResultItem.setSalary(item.getSalary());
                if (item.getMaritalStatus()==1){
                    jobInfoListResultItem.setMaritalStatus("已婚");
                }else {
                    jobInfoListResultItem.setMaritalStatus("未婚");
                }
                jobInfoListResultItem.setWorktime(item.getWorktime());
                jobInfoListResultItem.setEmail(item.getEmail());
                if (item.getWorkExperience()== null){
                    jobInfoListResultItem.setWorkExperience("无");
                }else {
                    jobInfoListResultItem.setWorkExperience(item.getWorkExperience());
                }
                jobInfoListResultItem.setAddress(item.getAddress());
                jobInfoListResultItem.setReleaseTime(ToolForDateTime.StringDateToYearMonthDay(ToolForDateTime.LocalDateTimeToStringToDate(item.getReleaseTime())));
                jobInfoListResultItem.setWorkAddress(item.getWorkAddress());
                jobInfoListResultItem.setJobType(item.getJobType());
                jobInfoList.add(jobInfoListResultItem);
            }
            result.setJobInfoList(jobInfoList);
            return ResponseWrapper.markSuccess(result);
        }else {
            // 登陆的不是管理员只查询当前登陆人的求职信息
            Integer totalNum = jobInforMapper.getLoginUserJobInfoTotalNum(param);
            result.setTotalNum(totalNum);

            List<Map<String, Object>> loginUserJobInfo = jobInforMapper.getLoginUserJobInfo(param);
            List<GetJobInfoListResultItem> allJobInfoList = CommonTool.mapListToBeanList(loginUserJobInfo, GetJobInfoListResultItem.class);

            for (GetJobInfoListResultItem item : allJobInfoList) {
                GetJobInfoListResultReal jobInfoListResultItem = new GetJobInfoListResultReal();
                jobInfoListResultItem.setAid(item.getAid());
                jobInfoListResultItem.setHuntUser(item.getHuntUser());
                if (item.getGender() == 1){
                    jobInfoListResultItem.setGender("男");
                }else {
                    jobInfoListResultItem.setGender("女");
                }
                jobInfoListResultItem.setPhone(item.getPhone());
                jobInfoListResultItem.setPosName(item.getPosName());
                jobInfoListResultItem.setSalary(item.getSalary());
                if (item.getMaritalStatus()==1){
                    jobInfoListResultItem.setMaritalStatus("已婚");
                }else {
                    jobInfoListResultItem.setMaritalStatus("未婚");
                }
                jobInfoListResultItem.setWorktime(item.getWorktime());
                jobInfoListResultItem.setEmail(item.getEmail());
                if (item.getWorkExperience()== null){
                    jobInfoListResultItem.setWorkExperience("无");
                }else {
                    jobInfoListResultItem.setWorkExperience(item.getWorkExperience());
                }
                jobInfoListResultItem.setAddress(item.getAddress());
                jobInfoListResultItem.setReleaseTime(ToolForDateTime.StringDateToYearMonthDay(ToolForDateTime.LocalDateTimeToStringToDate(item.getReleaseTime())));
                jobInfoListResultItem.setWorkAddress(item.getWorkAddress());
                jobInfoListResultItem.setJobType(item.getJobType());
                jobInfoList.add(jobInfoListResultItem);
            }
            result.setJobInfoList(jobInfoList);
            return ResponseWrapper.markSuccess(result);
        }


    }

    /**
     * 判断求职用户是否存在
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper checkHunterJobUserIsExist(CheckHunterJobUserIsExistParam param) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getName, param.getHuntJobUser())
        );
        if (user != null){
            return ResponseWrapper.markSuccess(true);
        }else {
            return ResponseWrapper.markSuccess(false);
        }
    }

    /**
     * 判断是否为管理员
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper isAdmin(CheckIsAdminParam param) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        if (user.getIsAdmin().equals(1)){
            return ResponseWrapper.markSuccess(true);
        }else {
            return ResponseWrapper.markSuccess(false);
        }
    }

    /**
     * 添加或者修改求职信息
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper editOrAddJobInfoApi(EditOrAddJobInfoParam param) {

        // 后端：通过account判断当前登陆的是否管理员，如果是管理员，就通过huntJobUser来添加或者修改求职信息（主要修改user_job表和job_infor表）
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        if (user.getIsAdmin().equals(1)){  // 管理员
            if (param.getAid().equals(-1)){  // 添加求职信息
                // 通过huntJobUser来查询用户
                User user1 = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getName, param.getHuntJobUser()));

                // 添加job_infor表
                JobInfor jobInfor = new JobInfor();
                JobInfor jobInfor1 = jobInforMapper.selectOne(new LambdaQueryWrapper<JobInfor>().orderByDesc(JobInfor::getAid).last("limit 1"));
                Integer addUserAid = jobInfor1.getAid() + 1;
                jobInfor.setAid(addUserAid);
                jobInfor.setSalary(param.getSalary());
                jobInfor.setPositionName(param.getJobName());
                jobInfor.setWorkTime(ToolForDateTime.UDateToLocalTime(param.getWorkTime()));
                jobInfor.setWorkAddress(param.getWorkAddress());
                jobInfor.setJobType(param.getJobType());
                jobInforMapper.insert(jobInfor);

                // 添加user_job表
                UserJob userJob = new UserJob();
                userJob.setUseraid(user1.getAid());
                userJob.setJobinfoaid(addUserAid);
                userJobMapper.insert(userJob);

                return ResponseWrapper.markCustomSuccess("添加成功！");

            }else {  // 修改求职信息

                JobInfor jobInfor = new JobInfor();
                jobInfor.setAid(param.getAid());
                jobInfor.setSalary(param.getSalary());
                jobInfor.setWorkTime(ToolForDateTime.UDateToLocalTime(param.getWorkTime()));
                jobInfor.setPositionName(param.getJobName());
                jobInfor.setWorkAddress(param.getWorkAddress());
                jobInfor.setJobType(param.getJobType());
                jobInforMapper.updateById(jobInfor);

                return ResponseWrapper.markCustomSuccess("修改成功！");

            }
        }else { // 不是管理员
            // 如果登陆的不是管理员，就通过account查询当前登陆人的姓名，
            // 通过当前登陆人的姓名来添加或者修改求职信息（主要修改user_job表和job_infor表）
            if (param.getAid().equals(-1)){  // 添加求职信息
                // 添加job_infor表
                JobInfor jobInfor = new JobInfor();
                JobInfor jobInfor1 = jobInforMapper.selectOne(new LambdaQueryWrapper<JobInfor>().orderByDesc(JobInfor::getAid).last("limit 1"));
                Integer addUserAid = jobInfor1.getAid() + 1;
                jobInfor.setAid(addUserAid);
                jobInfor.setSalary(param.getSalary());
                jobInfor.setPositionName(param.getJobName());
                jobInfor.setWorkTime(ToolForDateTime.UDateToLocalTime(param.getWorkTime()));
                jobInfor.setWorkAddress(param.getWorkAddress());
                jobInfor.setJobType(param.getJobType());
                jobInforMapper.insert(jobInfor);

                // 添加user_job表
                UserJob userJob = new UserJob();
                userJob.setUseraid(user.getAid());
                userJob.setJobinfoaid(addUserAid);
                userJobMapper.insert(userJob);

                return ResponseWrapper.markCustomSuccess("添加成功！");
            }else {
                // 修改求职信息
                JobInfor jobInfor = new JobInfor();
                UserJob userJob = userJobMapper.selectOne(new LambdaQueryWrapper<UserJob>().eq(UserJob::getAid, param.getAid()));
                jobInfor.setAid(userJob.getJobinfoaid());
                jobInfor.setSalary(param.getSalary());
                jobInfor.setWorkTime(ToolForDateTime.UDateToLocalTime(param.getWorkTime()));
                jobInfor.setPositionName(param.getJobName());
                jobInfor.setWorkAddress(param.getWorkAddress());
                jobInfor.setJobType(param.getJobType());
                jobInforMapper.updateById(jobInfor);

                return ResponseWrapper.markCustomSuccess("修改成功！");
            }
        }
    }

    /**
     * 删除求职信息
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper delJobInfoByAid(DelJobInfoByAidParam param) {

        // 删除user_job表
        userJobMapper.deleteById(param.getJobInfoAid());

        return ResponseWrapper.markCustomSuccess("删除成功！");

    }

    /**
     * 获取被点击用户的信息以及用户的求职信息
     *
     * @param param  参数类
     */
    @Override
    public ResponseWrapper getUserInfoAndJobInfo(GetUserInfoAndJobInfoParam param) {
        GetUserInfoAndJobInfoResult result = new GetUserInfoAndJobInfoResult();
        UserJob userJob = userJobMapper.selectById(param.getUserJobAid());
        User user = userMapper.selectById(userJob.getUseraid());
        result.setUserAid(user.getAid());
        result.setUserAvatar(user.getAvatar());
        result.setUserName(user.getName());
        result.setUserPhone(user.getPhone());
        result.setUserAddress(user.getAddress());
        if (user.getGender().equals(1)){
            result.setUserSex("男");
        }else {
            result.setUserSex("女");
        }
        result.setUserSchool(user.getSchool());
        result.setUserEmail(user.getEmail());

        // 查询这个用户所有招聘信息
        List<UserJob> userJobs = userJobMapper.selectList(new LambdaQueryWrapper<UserJob>().eq(UserJob::getUseraid, userJob.getUseraid()));

        ArrayList<GetUserInfoAndJobInfoResultChild> resultChildList = new ArrayList<>();
        for (UserJob job : userJobs) {
            JobInfor jobInfor = jobInforMapper.selectById(job.getJobinfoaid());
            GetUserInfoAndJobInfoResultChild resultChild = new GetUserInfoAndJobInfoResultChild();
            resultChild.setJobName(jobInfor.getPositionName());
            resultChild.setSalary(jobInfor.getSalary());
            resultChild.setWorkAddress(jobInfor.getWorkAddress());

            // 查询当前这个求职信息是否被登陆的企业收藏
            Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));


            resultChildList.add(resultChild);
        }
        result.setJobList(resultChildList);
        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 得到全部求职者信息和求职者发布的求职信息
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper getAllHunterInfoAndHunterPublishInfo(GetAllHunterInfoAndHunterPublishInfoParam param) {
        GetAllUserAndJobResult result = new GetAllUserAndJobResult();
        // 加工页码
        param.setPage((param.getPage() - 1) * param.getPageRow()); //处理分页条件

        // 加工搜索条件（hunterName）
        if (param.getHunterName() != null && !param.getHunterName().equals("")){
            param.setHunterName("%" + param.getHunterName() + "%");
        }
        // 加工搜索条件（positionName）
        if (param.getPositionName() != null && !param.getPositionName().equals("")){
            param.setPositionName("%" + param.getPositionName() + "%");
        }
        // 加工搜索条件（workAddress）
        if (param.getWorkAddress() != null && !param.getWorkAddress().equals("")){
            param.setWorkAddress("%" + param.getWorkAddress() + "%");
        }

        result.setJobInfoList(CommonTool.mapListToBeanList(userJobMapper.getHunterAndJob(param),GetAllUserAndJobItem.class));
        result.setTotalNum(userJobMapper.getHunterAndJobTotal(param));
        return ResponseWrapper.markSuccess(result);
    }
}
